<template>
  <div class="anypay-apple-list-page">
    <div class="anypay-apple-page-header">
      <h1>支付渠道接口管理</h1>
      <p>管理平台支持的支付渠道，配置渠道参数和接口信息</p>
    </div>

    <!-- 搜索区域 -->
    <div class="anypay-apple-card anypay-apple-mb-6">
      <a-card>
        <div class="search-container standard">
          <!-- 渠道接口名称 -->
          <div class="search-field">
            <label class="search-label">渠道接口名称:</label>
            <a-input
              v-model:value="searchForm.channelName"
              placeholder="请输入渠道接口名称"
              class="search-input"
              allowClear
              @press-enter="handleSearch"
            />
          </div>

          <!-- 状态 -->
          <div class="search-field">
            <label class="search-label">状态:</label>
            <a-select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              class="search-select"
              allowClear
            >
              <a-select-option :value="1">启用</a-select-option>
              <a-select-option :value="0">禁用</a-select-option>
            </a-select>
          </div>

          <!-- 操作按钮 -->
          <div class="search-actions">
            <a-button type="primary" @click="handleSearch" class="search-btn">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset" class="search-btn">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 数据表格区域 -->
    <div class="anypay-apple-card">
      <a-card>
        <div class="anypay-apple-table anypay-apple-toolbar">
          <AnyTable
            ref="channelTable"
            :autoLoad="true"
            :dataLoader="loadChannelData"
            :tableColumns="tableColumns"
            :searchParams="searchParams"
            :tableScroll="{ x: 'max-content' }"
            tableRowKey="channelId"
            @loadComplete="handleLoadComplete"
          >
            <template #tableToolbar>
              <a-space :size="12">
                <a-button type="primary" @click="handleCreate">
                  <PlusOutlined /> 新增渠道
                </a-button>
              </a-space>
            </template>
            <template #tableCell="{ column, record }">
              <template v-if="column.key === 'icon'">
                <img :src="record.iconUrl" :alt="record.channelName" style="width: 32px; height: 32px; object-fit: contain;" />
              </template>
              <template v-else-if="column.key === 'channelInfo'">
                <div>
                  <div style="font-weight: 500;">{{ record.channelName }}</div>
                  <div style="font-size: 12px; color: #666;">{{ record.channelCode }}</div>
                </div>
              </template>
              <template v-else-if="column.key === 'status'">
                <a-tag :color="getChannelStatusColor(record.status)">
                  {{ getChannelStatusName(record.status) }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'supportedProducts'">
                <div>
                  <a-tag
                    v-for="product in record.supportedProducts.slice(0, 3)"
                    :key="product"
                    size="small"
                    style="margin-bottom: 4px;"
                  >
                    {{ getProductName(product) }}
                  </a-tag>
                  <a-tag v-if="record.supportedProducts.length > 3" size="small" color="blue">
                    +{{ record.supportedProducts.length - 3 }}
                  </a-tag>
                </div>
              </template>
              <template v-else-if="column.key === 'testMode'">
                <a-tag :color="record.isTestMode ? 'orange' : 'green'">
                  {{ record.isTestMode ? '测试模式' : '生产模式' }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'supportMode'">
                <div>
                  <a-tag v-if="record.supportDirect" color="blue">直连</a-tag>
                  <a-tag v-if="record.supportProvider" color="green">服务商</a-tag>
                  <a-tag v-if="!record.supportDirect && !record.supportProvider" color="default">暂不支持</a-tag>
                </div>
              </template>
              <template v-else-if="column.key === 'features'">
                <div>
                  <a-tag v-if="record.supportTransaction" color="magenta">交易</a-tag>
                  <a-tag v-if="record.supportOnboarding" color="blue">进件</a-tag>
                  <a-tag v-if="record.supportReconciliation" color="green">对账</a-tag>
                  <a-tag v-if="record.supportWithdraw" color="orange">提现</a-tag>
                  <a-tag v-if="record.supportRefund" color="purple">退款</a-tag>
                  <a-tag v-if="record.supportProfitSharing" color="cyan">分账</a-tag>
                </div>
              </template>
              <template v-else-if="column.key === 'extraInfo'">
                <a-tooltip>
                  <template #title>
                    <pre>{{ JSON.stringify(record.extraInfo, null, 2) }}</pre>
                  </template>
                  <a-button type="link">查看详情</a-button>
                </a-tooltip>
              </template>
              <template v-else-if="column.key === 'action'">
                <div class="anypay-apple-actions">
                  <a-space>
                    <a-button type="link" @click="handleEdit(record)">
                      <EditOutlined />编辑
                    </a-button>
                    <a-dropdown placement="bottomRight">
                      <a-button type="link" size="small">
                        <MoreOutlined />
                        更多
                      </a-button>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item key="view" @click="handleView(record)">
                            <EyeOutlined />
                            查看
                          </a-menu-item>
                          <a-menu-item key="doc" @click="openDocUrl(record.apiDocUrl)" :disabled="!record.apiDocUrl">
                            <FileTextOutlined />
                            文档
                          </a-menu-item>
                          <a-menu-divider />
                          <a-menu-item key="toggle" @click="handleToggleStatus(record)">
                            {{ record.status === 1 ? '禁用' : '启用' }}
                          </a-menu-item>
                          <a-menu-divider />
                          <a-menu-item key="delete" @click="handleDelete(record)" style="color: #ff4d4f;">
                            删除
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </a-space>
                </div>
              </template>
            </template>
          </AnyTable>
        </div>
      </a-card>
    </div>

    <!-- 新增/编辑渠道对话框 -->
    <a-modal
      v-model:open="showEditDialog"
      :title="editDialogTitle"
      width="900px"
      :footer="null"
      class="channel-edit-modal"
    >
      <a-form
        ref="channelFormRef"
        :model="channelForm"
        :rules="channelRules"
        layout="vertical"
      >
        <a-card class="edit-section" title="基本信息" :bordered="false">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="渠道接口名称" name="channelName">
                <a-input v-model:value="channelForm.channelName" placeholder="请输入渠道接口名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="渠道图标URL" name="iconUrl">
                <a-input v-model:value="channelForm.iconUrl" placeholder="请输入渠道图标URL">
                  <template #suffix>
                    <img v-if="channelForm.iconUrl" :src="channelForm.iconUrl" :alt="channelForm.channelName" style="width: 20px; height: 20px; object-fit: contain;" />
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <a-card class="edit-section" title="接口配置" :bordered="false">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="生产环境API" name="apiUrl">
                <a-input v-model:value="channelForm.apiUrl" placeholder="请输入生产环境API地址">
                  <template #prefix>
                    <ApiOutlined />
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="测试环境API" name="testApiUrl">
                <a-input v-model:value="channelForm.testApiUrl" placeholder="请输入测试环境API地址">
                  <template #prefix>
                    <ExperimentOutlined />
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="接口文档" name="apiDocUrl">
            <a-input v-model:value="channelForm.apiDocUrl" placeholder="请输入接口文档地址">
              <template #prefix>
                <FileTextOutlined />
              </template>
              <template #suffix>
                <a-button
                  type="link"
                  size="small"
                  @click="openDocUrl(channelForm.apiDocUrl)"
                  :disabled="!channelForm.apiDocUrl"
                >
                  <LinkOutlined />
                  打开文档
                </a-button>
              </template>
            </a-input>
          </a-form-item>
        </a-card>

        <a-card class="edit-section" title="其他配置" :bordered="false">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="结算周期" name="settlementCycle">
                <a-select v-model:value="channelForm.settlementCycle" placeholder="请选择结算周期">
                  <a-select-option value="T+0">T+0</a-select-option>
                  <a-select-option value="T+1">T+1</a-select-option>
                  <a-select-option value="T+2">T+2</a-select-option>
                  <a-select-option value="T+7">T+7</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="运行模式" name="isTestMode">
                <a-radio-group v-model:value="channelForm.isTestMode" button-style="solid">
                  <a-radio-button :value="false">生产模式</a-radio-button>
                  <a-radio-button :value="true">测试模式</a-radio-button>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="状态" name="status">
                <a-select v-model:value="channelForm.status">
                  <a-select-option :value="1">启用</a-select-option>
                  <a-select-option :value="0">禁用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <div class="form-footer">
          <a-space>
            <a-button @click="handleCancelChannel">取消</a-button>
            <a-button type="primary" @click="handleSaveChannel">保存</a-button>
          </a-space>
        </div>
      </a-form>
    </a-modal>


    <!-- 查看渠道对话框 -->
    <a-modal
      v-model:open="showViewDialog"
      title="查看渠道详情"
      width="900px"
      :footer="null"
      class="channel-view-modal"
    >
      <a-descriptions bordered>
        <a-descriptions-item label="渠道图标">
          <img :src="viewingChannel.iconUrl" :alt="viewingChannel.channelName" style="width: 48px; height: 48px; object-fit: contain;" />
        </a-descriptions-item>
        <a-descriptions-item label="渠道接口名称">
          {{ viewingChannel.channelName }}
        </a-descriptions-item>
        <a-descriptions-item label="渠道接口代码">
          {{ viewingChannel.channelCode }}
        </a-descriptions-item>

        <a-descriptions-item label="生产环境API" :span="3">
          {{ viewingChannel.apiUrl }}
        </a-descriptions-item>

        <a-descriptions-item label="测试环境API" :span="3">
          {{ viewingChannel.testApiUrl }}
        </a-descriptions-item>

        <a-descriptions-item label="接口文档" :span="3">
          <a :href="viewingChannel.apiDocUrl" target="_blank">{{ viewingChannel.apiDocUrl }}</a>
        </a-descriptions-item>

        <a-descriptions-item label="商户接入模式" :span="3">
          <a-space>
            <a-tag v-if="viewingChannel.supportDirect" color="blue">
              直连
            </a-tag>
            <a-tag v-if="viewingChannel.supportProvider" color="green">
              服务商
            </a-tag>
            <a-tag v-if="!viewingChannel.supportDirect && !viewingChannel.supportProvider" color="default">
              暂不支持
            </a-tag>
          </a-space>
        </a-descriptions-item>

        <a-descriptions-item label="核心功能" :span="3">
          <a-space>
            <a-tag :color="viewingChannel.supportTransaction ? 'magenta' : 'default'">
              {{ viewingChannel.supportTransaction ? '支持交易' : '不支持交易' }}
            </a-tag>
            <a-tag :color="viewingChannel.supportRefund ? 'purple' : 'default'">
              {{ viewingChannel.supportRefund ? '支持退款' : '不支持退款' }}
            </a-tag>
            <a-tag :color="viewingChannel.supportProfitSharing ? 'cyan' : 'default'">
              {{ viewingChannel.supportProfitSharing ? '支持分账' : '不支持分账' }}
            </a-tag>
          </a-space>
        </a-descriptions-item>

        <a-descriptions-item label="增值功能" :span="3">
          <a-space>
            <a-tag :color="viewingChannel.supportOnboarding ? 'blue' : 'default'">
              {{ viewingChannel.supportOnboarding ? '支持进件' : '不支持进件' }}
            </a-tag>
            <a-tag :color="viewingChannel.supportReconciliation ? 'green' : 'default'">
              {{ viewingChannel.supportReconciliation ? '支持对账' : '不支持对账' }}
            </a-tag>
            <a-tag :color="viewingChannel.supportWithdraw ? 'orange' : 'default'">
              {{ viewingChannel.supportWithdraw ? '支持提现' : '不支持提现' }}
            </a-tag>
          </a-space>
        </a-descriptions-item>

        <a-descriptions-item label="支持产品" :span="3">
          <div class="product-list">
            <a-row :gutter="[16, 16]">
              <a-col :span="8" v-for="productCode in viewingChannel.supportedProducts" :key="productCode">
                <a-tag class="product-tag">
                  <template #icon>
                    <check-circle-outlined />
                  </template>
                  {{ getProductName(productCode) }}
                </a-tag>
              </a-col>
            </a-row>
          </div>
        </a-descriptions-item>

        <a-descriptions-item label="结算周期">
          {{ viewingChannel.settlementCycle }}
        </a-descriptions-item>
        <a-descriptions-item label="运行模式">
          <a-tag :color="viewingChannel.isTestMode ? 'orange' : 'green'">
            {{ viewingChannel.isTestMode ? '测试模式' : '生产模式' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getChannelStatusColor(viewingChannel.status)">
            {{ getChannelStatusName(viewingChannel.status) }}
          </a-tag>
        </a-descriptions-item>

        <a-descriptions-item label="额外配置" :span="3">
          <pre class="extra-info-pre">{{ JSON.stringify(viewingChannel.extraInfo, null, 2) }}</pre>
        </a-descriptions-item>

        <a-descriptions-item label="创建时间">
          {{ viewingChannel.createdTime }}
        </a-descriptions-item>
        <a-descriptions-item label="更新时间" :span="2">
          {{ viewingChannel.updatedTime }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  ApiOutlined,
  ExperimentOutlined,
  FileTextOutlined,
  LinkOutlined,
  CheckCircleOutlined,
  EditOutlined,
  EyeOutlined,
  SearchOutlined,
  ReloadOutlined,
  MoreOutlined
} from '@ant-design/icons-vue'
import {
  paymentChannels,
  getChannelStatusName,
  getChannelStatusColor,
  type PaymentChannel
} from '@/mock/channels'

import {
  paymentProducts
} from '@/mock/products'


import AnyTable from '@/components/AnyTable.vue'

// 响应式数据
const showEditDialog = ref(false)

// 组件引用
const channelTable = ref()
const channelFormRef = ref()

// 表单数据
const searchForm = reactive({
  channelName: '',
  status: undefined
})

// 搜索参数
const searchParams = reactive<{
  channelName?: string
  status?: number
}>({})

const channelForm = reactive<PaymentChannel>({
  channelId: '',
  channelName: '',
  channelCode: '',
  iconUrl: '',
  apiUrl: '',
  testApiUrl: '',
  apiDocUrl: '',
  supportedProducts: [],
  settlementCycle: 'T+1',
  status: 1,
  isTestMode: false,
  createdTime: new Date().toISOString(),
  updatedTime: new Date().toISOString(),
  supportProvider: false,
  supportDirect: false,
  supportOnboarding: false,
  supportReconciliation: false,
  supportWithdraw: false,
  supportRefund: false,
  supportProfitSharing: false,
  supportTransaction: false,
  extraInfo: {}
})



// 编辑对话框标题
const editDialogTitle = computed(() => {
  return channelForm.channelId ? '编辑渠道' : '新增渠道'
})



// 表格列定义
const tableColumns = [
  {
    title: '渠道图标',
    key: 'icon',
    width: 80,
    align: 'center'
  },
  {
    title: '渠道信息',
    key: 'channelInfo',
    width: 200
  },
  {
    title: '商户接入模式',
    key: 'supportMode',
    width: 120
  },
  {
    title: '支持功能',
    key: 'features',
    width: 300,
    visible: false
  },
  {
    title: '额外配置',
    key: 'extraInfo',
    width: 100,
    align: 'center',
    visible: false
  },
  {
    title: '结算周期',
    dataIndex: 'settlementCycle',
    key: 'settlementCycle',
    width: 100,
    align: 'center',
    visible: false
  },
  {
    title: '运行模式',
    key: 'testMode',
    width: 100,
    align: 'center'
  },
  {
    title: '状态',
    key: 'status',
    width: 80,
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    width: 220,
    align: 'center'
  }
]

// 表单验证规则
const channelRules = {
  channelName: [
    { required: true, message: '请输入渠道接口名称', trigger: 'blur' }
  ],
  apiUrl: [
    { required: true, message: '请输入API地址', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' }
  ],
  settlementCycle: [
    { required: true, message: '请选择结算周期', trigger: 'change' }
  ]
}

// 数据加载函数
const loadChannelData = async (params: any) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    let filteredData = [...paymentChannels]

    // 应用搜索筛选
    if (params.channelName) {
      filteredData = filteredData.filter(item =>
        item.channelName.toLowerCase().includes(params.channelName.toLowerCase())
      )
    }

    if (params.status !== undefined) {
      filteredData = filteredData.filter(item => item.status === params.status)
    }

    // 计算分页
    const startIndex = ((params.pageNumber || 1) - 1) * (params.pageSize || 10)
    const endIndex = startIndex + (params.pageSize || 10)
    const records = filteredData.slice(startIndex, endIndex)

    return {
      records,
      total: filteredData.length,
      pageNumber: params.pageNumber || 1,
      pageSize: params.pageSize || 10
    }
  } catch (error) {
    console.error('Failed to load channel data:', error)
    return { records: [], total: 0, pageNumber: 1, pageSize: 10 }
  }
}

// 加载完成回调
const handleLoadComplete = () => {
  console.log('Channel data loaded successfully')
}

// 方法
const handleCreate = () => {
  resetChannelForm()
  showEditDialog.value = true
}

const handleEdit = (record: PaymentChannel) => {
  Object.assign(channelForm, record)
  showEditDialog.value = true
}

const handleDelete = (record: PaymentChannel) => {
  message.success(`删除渠道 ${record.channelName} 成功`)
  searchChannels()
}

const handleToggleStatus = (record: PaymentChannel) => {
  const newStatus = record.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '启用' : '禁用'

  record.status = newStatus
  message.success(`${action}渠道成功`)
}

const handleSearch = () => {
  // 清空之前的搜索参数
  Object.keys(searchParams).forEach(key => {
    delete (searchParams as any)[key]
  })

  // 只添加非空的搜索条件
  if (searchForm.channelName) {
    searchParams.channelName = searchForm.channelName
  }
  if (searchForm.status !== undefined) {
    searchParams.status = searchForm.status
  }

  searchChannels()
}

const handleReset = () => {
  // 清空搜索表单
  Object.assign(searchForm, {
    channelName: '',
    status: undefined
  })

  // 清空搜索参数
  Object.keys(searchParams).forEach(key => {
    delete (searchParams as any)[key]
  })

  searchChannels()
}

// 搜索渠道
const searchChannels = () => {
  channelTable.value?.refreshTable(true)
}

// handleTableChange 已由 AnyTable 内部处理，不再需要

const handleSaveChannel = async () => {
  try {
    if (channelForm.channelId) {
      message.success('编辑渠道成功')
    } else {
      channelForm.channelId = generateChannelId()
      message.success('新增渠道成功')
    }
    showEditDialog.value = false
    searchChannels()
  } catch (error) {
    message.error('保存失败')
  }
}

const handleCancelChannel = () => {
  showEditDialog.value = false
  resetChannelForm()
}

const resetChannelForm = () => {
  Object.assign(channelForm, {
    channelId: '',
    channelName: '',
    channelCode: '',
    iconUrl: '',
    apiUrl: '',
    testApiUrl: '',
    apiDocUrl: '',
    supportedProducts: [],
    settlementCycle: 'T+1',
    status: 1,
    isTestMode: false,
    createdTime: new Date().toISOString(),
    updatedTime: new Date().toISOString(),
    supportProvider: false,
    supportDirect: false,
    supportOnboarding: false,
    supportReconciliation: false,
    supportWithdraw: false,
    supportRefund: false,
    supportProfitSharing: false,
    supportTransaction: false,
    extraInfo: {}
  })
}

const generateChannelId = () => {
  return 'CH' + Date.now().toString().slice(-6)
}

// loadData 已由 AnyTable 的 autoLoad 处理

// 打开文档链接
const openDocUrl = (url: string): void => {
  if (url) {
    window.open(url, '_blank')
  }
}

// 根据产品代码获取产品名称
const getProductName = (code: string): string => {
  const product = paymentProducts.find(p => p.productCode === code)
  return product ? product.productName : code
}

// loadData 和 onMounted 已由 AnyTable 的 autoLoad 处理

// 查看对话框状态
const showViewDialog = ref(false)
const viewingChannel = reactive<PaymentChannel>({
  channelId: '',
  channelName: '',
  channelCode: '',
  iconUrl: '',
  apiUrl: '',
  testApiUrl: '',
  apiDocUrl: '',
  supportedProducts: [],
  settlementCycle: 'T+1',
  status: 1,
  isTestMode: false,
  createdTime: '',
  updatedTime: '',
  supportProvider: false,
  supportDirect: false,
  supportOnboarding: false,
  supportReconciliation: false,
  supportWithdraw: false,
  supportRefund: false,
  supportProfitSharing: false,
  supportTransaction: false,
  extraInfo: {}
})

// 查看渠道
const handleView = (record: PaymentChannel) => {
  Object.assign(viewingChannel, record)
  showViewDialog.value = true
}







// 组件初始化
onMounted(() => {
  // 组件初始化完成
})
</script>

<style scoped>
@import '../common/list-page.css';

/* 对话框样式 */
.channel-edit-modal {
  :deep(.ant-modal-body) {
    padding: 0;
  }
}

.edit-section {
  margin-bottom: 16px;

  :deep(.ant-card-head) {
    padding: 8px 16px;
    min-height: 40px;
    background: #fafafa;
    border-bottom: 1px solid #f0f0f0;
  }

  :deep(.ant-card-body) {
    padding: 16px;
  }
}

.form-footer {
  padding: 16px;
  text-align: right;
  background: #fff;
  border-top: 1px solid #f0f0f0;
}

:deep(.ant-form-item-label) {
  font-weight: 500;
}

.product-list {
  padding: 8px;
}

.product-tag {
  width: 100%;
  text-align: center;
  font-size: 14px;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f6f6f6;
  border: 1px solid #e8e8e8;
  color: #333;
}

.product-tag :deep(.anticon) {
  color: #52c41a;
  margin-right: 6px;
}

.extra-info-pre {
  background-color: #fafafa;
  padding: 12px;
  border-radius: 4px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 12px;
  max-height: 200px;
  overflow: auto;
}

.channel-view-modal {
  :deep(.ant-descriptions-item-label) {
    width: 120px;
    background-color: #fafafa;
  }

  :deep(.ant-descriptions-item-content) {
    padding: 12px 16px;
  }
}





.channel-icon {
  width: 48px;
  height: 48px;
  object-fit: contain;
  background: white;
  border-radius: 8px;
  padding: 4px;
}

.channel-details h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: white;
}

.channel-details p {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
  color: white;
}











:deep(.ant-form-item) {
  margin-bottom: 12px;
}

:deep(.ant-form-item-label) {
  font-weight: 500;
}
</style>